package org.han.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public abstract class BaseDao<T>{
	private Class entityClass;
	protected SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public BaseDao() {
		super();
		// TODO Auto-generated constructor stub
		entityClass = getParameterizedType(this.getClass());
	}

	/*
	 * 获得当前类的Class
	 */
	private Class getParameterizedType(Class c) {
		Type type = c.getGenericSuperclass();
		ParameterizedType parametType = null;
		if (type instanceof ParameterizedType) {
			parametType = (ParameterizedType) type;
		} else {
			try {
				throw new Exception("not find ParameterizedType!");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Type[] types = parametType.getActualTypeArguments();
		return (Class) types[0];
	}

	/*
	 * 通用通过ID获得实体类的方法
	 */
	protected T getEntityById(Integer primaryKey) {
		try{
		System.out.println(sessionFactory.getCurrentSession());
		}catch (Exception e) {
			e.printStackTrace();
		}
		Session session = this.sessionFactory.getCurrentSession();
		T t = (T) session.get(this.entityClass, primaryKey);
		return t;
	}
	/*
	 * 公用的save方法
	 */
	public int saveObject(Object obj){
		return (Integer)this.sessionFactory.getCurrentSession().save(obj);
	}
}
